package com.hongxun.design.activitys;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.MultiSelecMoreAdapter;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.MaterialBean;
import com.hongxun.design.bean.MaterialsBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.jungong.model.MatreialDetailSys;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zerdoor_pc on 2016/5/27.
 */
public class MultiselectActivity extends BaseActivity implements HeadSecond, SwipeRefreshLayout.OnRefreshListener {
    String title = "多选";
    /**
     * MString.Modular_Pro://模块添加材料
     * MString.MaterialScience://点设添加材料/点位添加材料
     * MString.Modular://点设添加模块/点位添加模块
     */
    String type;
    String codeset_version_id;

//    int s = 0;
//    int n = 100;
    /**
     * 通用控件*
     */
    SwipeRefreshListView multiselect_list;
    List<MaterialsBean> data;
    MultiSelecMoreAdapter adapter;
    EditText words;
    /**
     * 材料Handler*
     */
    Handler materialScienceHandler;
    /**
     * 模块Handler*
     */
    Handler modularHandler;
    Handler finishHandler;
    String codeset_id;
    Spinner spinner;

    @Override
    protected void onDestroy() {
        data = null;
        adapter = null;
        multiselect_list = null;
        materialScienceHandler = null;
        finishHandler = null;
        modularHandler = null;
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multiselect);
        findBar();
        findView();
    }

    @Override
    public void findBar() {
        getIntentData();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.design_head);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("确认", View.VISIBLE, R.color.bar_right,
                ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<MaterialsBean> beans = (List<MaterialsBean>) adapter.getChecked();
                if (beans.size() == 0) {
                    ToastShow.showShort(mActivity, "请至少选择一条数据！");
                    return;
                }
                showWaitDialog(-1, "处理中...");
                String ids = "";
                switch (type) {
                    case MString.MaterialScience:
                        for (MaterialsBean b : beans) {
                            ids += b.getMaterial_id() + "|";
                        }
                        switch (getIntent().getExtras().getString(MString.TRUE)) {
                            case "典设":
                                MyApp.HTTP.ImpProMaterial(finishHandler, HttpStringUtil.SUCCESSED, ids, codeset_id);
                                break;
                            case "点位":
                                if (MyApp.NetWorkConnect) {
                                    MyApp.HTTP.ImpExpMaterial(finishHandler, HttpStringUtil.SUCCESSED, ids);
                                } else {
                                    pointAddMaterials(beans);
                                }
                                break;
                            default:
                                MyApp.HTTP.ImpProMaterial(finishHandler, HttpStringUtil.SUCCESSED, ids, codeset_id);
                                break;
                        }
                        break;
                    case MString.Modular:
                        for (MaterialsBean b : beans) {
                            ids += b.getModule_id() + "|";
                        }
                        switch (getIntent().getExtras().getString(MString.TRUE)) {
                            case "典设":
                                MyApp.HTTP.ImpMaterial2odel(finishHandler, HttpStringUtil.SUCCESSED, ids, codeset_id);
                                break;
                            case "点位":
                                if (MyApp.NetWorkConnect) {
                                    MyApp.HTTP.ImpExpModule(finishHandler, HttpStringUtil.SUCCESSED, ids);
                                } else {
                                    pointAddModular(beans);
                                }
                                break;
                            default:
                                MyApp.HTTP.ImpProMaterial(finishHandler, HttpStringUtil.SUCCESSED, ids, codeset_id);
                                break;
                        }
                        break;
                    case MString.Modular_Pro://模块添加材料
                        for (MaterialsBean b : beans) {
                            ids += b.getMaterial_number() + "|";
                        }
                        MyApp.HTTP.ImpProModelMaterial(finishHandler, HttpStringUtil.SUCCESSED, ids, codeset_id);
                        break;
                }
                //((Activity) view.getContext()).finish();
            }
        });
    }

    //nx点位选择的模块存到xml
    private void pointAddModular(List<MaterialsBean> beans) {
        savePoints();
        //点位模块存储
        List<MaterialBean> list = new ArrayList<>();
        for (MaterialsBean b : beans) {
            MaterialBean bean = new MaterialBean();
            bean.setMaterial_number(b.getModule_id());//本地模块、点设模块、服务器模块
            bean.setName(b.getName());
            bean.setSpec(b.getSpec());
            bean.setNum("1");
            bean.setUnit(b.getUnit());
            bean.setObj_type("1");//模块
            bean.setUse_type(MString.OLD);
            list.add(bean);
        }
        String key = MString.nxPointModel + MyApp.currExploration.getExploration_id();
        String nxPointModel = ShardPreferencesTool.read(getApplicationContext(), key, "", 3);
        List<MaterialBean> list1 = JSON.parseArray(nxPointModel, MaterialBean.class);
        if (list1 != null) {
            boolean isAdd = true;
            List<MaterialBean> list2 = new ArrayList<>();
            for (MaterialBean mbean : list) {
                for (MaterialBean bean1 : list1) {
                    if (bean1.getSpec().equals(mbean.getSpec())) {//型号一致
                        String number = bean1.getMaterial_number();
                        if (number != null && number.equals(mbean.getMaterial_number())) {
                            double aDouble = Double.valueOf(bean1.getNum()) + 1;
                            bean1.setNum(aDouble + "");
                            isAdd = false;
                            break;
                        }
                    }
                }
                if (isAdd) {
                    list2.add(mbean);
                }
            }
            list1.addAll(list2);
        } else {
            list1 = new ArrayList<>();
            list1.addAll(list);
        }
        ShardPreferencesTool.save(getApplicationContext(), key, FastJsonUtil.beanToJson(list1), 3);
        finishHandler.sendEmptyMessage(1001);
    }

    //nx点位选择的材料存到xml
    private void pointAddMaterials(List<MaterialsBean> beans) {
        savePoints();
        //点位材料存储
        List<MaterialBean> list = new ArrayList<>();
        for (MaterialsBean b : beans) {
            MaterialBean bean = new MaterialBean();
            bean.setMaterial_id(b.getMaterial_id());
            bean.setMaterial_number(b.getMaterial_number());//本地材料、点设材料、服务器材料
            bean.setName(b.getName());
            bean.setSpec(b.getSpec());
            bean.setNum("1");
            bean.setUnit(b.getUnit());
            bean.setObj_type("0");//材料
            bean.setUse_type(MString.OLD);
            list.add(bean);
        }
        String key = MString.nxPointMaterial + MyApp.currExploration.getExploration_id();
        String nxPointMaterial = ShardPreferencesTool.read(getApplicationContext(), key, "", 3);
        List<MaterialBean> list1 = JSON.parseArray(nxPointMaterial, MaterialBean.class);
        if (list1 != null) {
            boolean isAdd = true;
            List<MaterialBean> list2 = new ArrayList<>();
            for (MaterialBean mbean : list) {
                for (MaterialBean bean1 : list1) {
                    if (bean1.getSpec().equals(mbean.getSpec())) {
                        //判断number
                        String number = bean1.getMaterial_number();
                        if (number != null && number.equals(mbean.getMaterial_number())) {
                            double aDouble = Double.valueOf(bean1.getNum()) + 1;
                            bean1.setNum(aDouble + "");
                            isAdd = false;
                            break;
                        }
                    }
                }
                if (isAdd) {
                    list2.add(mbean);
                }
            }
            list1.addAll(list2);
        } else {
            list1 = new ArrayList<>();
            list1.addAll(list);
        }
        ShardPreferencesTool.save(getApplicationContext(), key, FastJsonUtil.beanToJson(list1), 3);
        finishHandler.sendEmptyMessage(1001);
    }

    //nx项目点位信息存储
    private void savePoints() {
        String read = ShardPreferencesTool.read(getApplicationContext(), MyApp.currProject.getProject_id(), "", 3);
        List<Exploration> listEP = JSON.parseArray(read, Exploration.class);
        if (listEP == null) listEP = new ArrayList<>();
        boolean isNewPoint = true;
        for (Exploration exp : listEP) {
            if (exp.getExploration_id().equals(MyApp.currExploration.getExploration_id())) {
                isNewPoint = false;
            }
        }
        if (isNewPoint) listEP.add(MyApp.currExploration);
        ShardPreferencesTool.save(getApplicationContext(), MyApp.currProject.getProject_id(), FastJsonUtil.beanToJson(listEP), 3);
    }

    private void getIntentData() {
        type = getIntent().getExtras().getString(MString.TYPE);
        codeset_id = getIntent().getExtras().getString(MString.ERROR);//典设ID
        codeset_version_id = MyApp.currProject.getCodeset_version_id();
        switch (type) {
            case MString.MaterialScience:
                title = "选择材料";
                break;
            case MString.Modular:
                title = "选择模块";
                break;
            case MString.Modular_Pro:
                title = "选择材料";
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        mActivity = this;
        MyApp.activity = this;
        super.onResume();
    }

    private ArrayAdapter<String> adapter_sp;

    @Override
    protected void findView() {
        super.findView();
        spinner = (Spinner) findViewById(R.id.spinner);
        words = (EditText) findViewById(R.id.serch_words);
        findViewForAll();
        initialization();

        adapter_sp = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mItems);
        adapter_sp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter_sp);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                typeItem = mItems.get(position);
                getMaterialList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void search(View v) {
        name = words.getText().toString();
        onRefresh();
    }

    //通用控件
    private void findViewForAll() {
        multiselect_list = (SwipeRefreshListView) findViewById(R.id.multiselect_list);
        multiselect_list.setOnRefreshListener(this);
    }

    @Override
    public void addMore() {
        if (!MyApp.NetWorkConnect) {
            multiselect_list.setRefreshing(false);
            multiselect_list.removeFooterView();
            return;
        }
        super.addMore();
        switch (type) {
            case MString.Modular_Pro:
            case MString.MaterialScience:
                startNum = addNum;
                addNum += 15;

                MyApp.HTTP.getMaterialList1(materialScienceHandler, HttpStringUtil.ADDMROE, name, typeItem,
                        codeset_version_id, startNum, MyApp.addNum);
                break;
            case MString.Modular:
                getModelListData();
                break;
        }
    }

    @Override
    protected void initialization() {
        super.initialization();
        switch (type) {
            case MString.Modular_Pro://模块添加材料
            case MString.MaterialScience://点设添加材料/点位添加材料
                initializationForMaterialScience();
                break;
            case MString.Modular://点设添加模块/点位添加模块
                initializationForModular();
                break;
        }
        addFinishHandler();
    }

    int startNum = 0;
    int addNum = MyApp.addNum;
    String name = "";

    //新增材料初始化
    void initializationForMaterialScience() {
        addMaterialScienceHandler();
        getMaterialList();
        getType();
    }

    //首次或刷新请求——材料
    private void getMaterialList() {
        if (MyApp.NetWorkConnect) {
            startNum = 0;
            addNum = MyApp.addNum;
            getMaterialListData();
        } else {
            //nx读取项目缓存材料
            String readM = ShardPreferencesTool.read(getApplicationContext(), MString.nxMaterialImp, "", 3);
            List<MatreialDetailSys> details = JSON.parseArray(readM, MatreialDetailSys.class);
            if (details == null) details = new ArrayList<>();
            if (data == null) data = new ArrayList<>();
            else data.clear();
            for (MatreialDetailSys detail : details) {
                boolean isAdd = false;
                if (TextUtils.isEmpty(name)) {
                    isAdd = true;
                } else {
                    if (detail.getName().contains(name)) {
                        isAdd = true;
                    }
                }
                if (isAdd) {
                    MaterialsBean bean = new MaterialsBean();
                    bean.setMaterial_id(detail.getMaterial_id() + "");
                    bean.setMaterial_number(detail.getMaterial_number());
                    bean.setErp_code(detail.getErp_code());
                    bean.setName(detail.getName());
                    bean.setSpec(detail.getSpec());
                    bean.setUnit(detail.getUnit());
                    bean.setNum(detail.getNum() + "");
                    bean.setIs_wire(detail.getIs_wire() + "");
                    data.add(bean);
                }
            }
            materialScienceHandler.sendEmptyMessage(1);
        }
    }

    String typeItem = "";
    List<String> mItems = new ArrayList<>();

    void addMaterialScienceHandler() {
        materialScienceHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 9080://获取type
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            mItems.clear();
                            mItems.add("全部");
                            try {
                                mItems.addAll(JSON.parseObject(new JSONObject((String) msg.obj).getString("type"), new TypeReference<List<String>>() {
                                }));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            adapter_sp.notifyDataSetChanged();
//                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MultiselectActivity.this, android.R.layout.simple_spinner_item, mItems);
//                            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//                            spinner.setAdapter(adapter);
//                            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                @Override
//                                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                    typeItem = mItems.get(position);
//                                    getMaterialList();
//                                }
//
//                                @Override
//                                public void onNothingSelected(AdapterView<?> parent) {
//
//                                }
//                            });
                        }
                        break;
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                data = FastJsonUtil.JsonToData_MaterialList((String) msg.obj);
                            } else {
                                data.clear();
                                data.addAll(FastJsonUtil.JsonToData_MaterialList((String) msg.obj));

                            }
                            materialScienceHandler.sendEmptyMessage(1);
                        }
                        break;
                    case 1:
                        if (adapter == null) {
                            adapter = new MultiSelecMoreAdapter(data, mActivity);
                            multiselect_list.setAdapter(adapter);
                            multiselect_list.setFragment(baseActivity);
                            multiselect_list.setCanScroll(true);
                        } else {
                            adapter.Refresh();
                            multiselect_list.update();
                            multiselect_list.setRefreshing(false);
                            multiselect_list.removeFooterView();
                        }

                        break;
                    case HttpStringUtil.ADDMROE:
                        List<MaterialsBean> been;
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                been = FastJsonUtil.JsonToData_MaterialList((String) msg.obj);
                                data = been;
                            } else {
                                been = new ArrayList<>();
                                been.addAll(FastJsonUtil.JsonToData_MaterialList((String) msg.obj));
                                data.addAll(been);
                            }
                            materialScienceHandler.sendEmptyMessage(1);
                            if (been.isEmpty()) {
                                ToastShow.showShort(mActivity, "没有数据了");
                            }
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;

                }
            }
        };
    }

    //新增模块初始化
    void initializationForModular() {
        addModularHandler();
        getModuleList();
    }

    void getModuleList() {
        if (MyApp.NetWorkConnect) {
            startNum = 0;
            addNum = MyApp.addNum;
            getModelListData();
        } else {
            //nx读取项目缓存模块
            String readM = ShardPreferencesTool.read(getApplicationContext(), MString.nxModelAdd, "", 3);
            List<MaterialsBean> details = JSON.parseArray(readM, MaterialsBean.class);
            if (details == null) details = new ArrayList<>();
            if (data == null) data = new ArrayList<>();
            else data.clear();
            for (MaterialsBean bean : details) {
                boolean isAdd = false;
                if (TextUtils.isEmpty(name)) {
                    isAdd = true;
                } else {
                    if (bean.getName().contains(name)) {
                        isAdd = true;
                    }
                }
                if (isAdd) {
                    data.add(bean);
                }
            }
            modularHandler.sendEmptyMessage(1);
        }
    }

    void addModularHandler() {
        modularHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                data = FastJsonUtil.JsonToData_ModuleList((String) msg.obj);
                            } else {
                                data.clear();
                                data.addAll(FastJsonUtil.JsonToData_ModuleList((String) msg.obj));
                            }

                            if (data != null) {
                                MyLog.L(MString.SUCCESSED + " JSON=" + data.size());
                            }
                            MyLog.L(MString.SUCCESSED + " JSON=" + JSON.toJSONString(data));
                            modularHandler.sendEmptyMessage(1);
                            startNum = startNum + addNum;
                        }
                        break;
                    case 1:
                        if (adapter == null) {
                            adapter = new MultiSelecMoreAdapter(data, mActivity);
                            multiselect_list.setAdapter(adapter);
                            multiselect_list.setFragment(baseActivity);
                            multiselect_list.setCanScroll(true);
                        } else {
                            adapter.Refresh();
                            multiselect_list.update();
                            multiselect_list.setRefreshing(false);
                            multiselect_list.removeFooterView();
                        }

                        break;
                    case HttpStringUtil.ADDMROE:
                        int num = 0;
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                data = FastJsonUtil.JsonToData_ModuleList((String) msg.obj);
                            } else {
                                num = Integer.parseInt(data.size() + "");
                                data.addAll(FastJsonUtil.JsonToData_ModuleList((String) msg.obj));
                            }

                            if (data != null) {
                                MyLog.L(MString.SUCCESSED + " JSON=" + data.size());
                            }
                            MyLog.L(MString.SUCCESSED + " JSON=" + JSON.toJSONString(data));
                            modularHandler.sendEmptyMessage(1);
                            if (num < data.size()) {
                                startNum = startNum + addNum;
                            } else {
                                ToastShow.showShort(mActivity, "没有数据了");
                            }
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        hideWaitIngDialog();
                        break;

                }
            }
        };
    }

    void addFinishHandler() {
        finishHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE)) {
                            finishHandler.sendEmptyMessage(1);
                        } else {
                            hideWaitIngDialog();
                            ToastShow.showShort(mActivity, s);
                        }
                        break;
                    case 1:
                        new Timer().schedule(new TimerTask() {
                            @Override
                            public void run() {
                                finishHandler.sendEmptyMessage(1001);
                            }
                        }, 1000);
                        break;
                    case HttpStringUtil.ERROR:
                        hideWaitIngDialog();
                        break;
                    case 1001:
                        hideWaitIngDialog();
                        mActivity.finish();
                        break;

                }
            }
        };
    }

    @Override
    public void onRefresh() {
        name = words.getText().toString();
        adapter.map = null;
        switch (type) {
            case MString.Modular_Pro:
            case MString.MaterialScience:
                getMaterialList();
                break;
            case MString.Modular://点设选择模块
                getModuleList();
                break;
        }
    }

    // 获取模块材料数据
    private void getModelListData() {
        MyApp.HTTP.getModuleList1(modularHandler, HttpStringUtil.SUCCESSED, name, codeset_version_id,
                startNum, MyApp.addNum);
    }

    // 获取材料数据
    private void getMaterialListData() {
        MyApp.HTTP.getMaterialList1(materialScienceHandler, HttpStringUtil.SUCCESSED, name, typeItem,
                codeset_version_id, startNum, MyApp.addNum);
    }

    private void getType() {
        MyApp.HTTP.getMaterialType(materialScienceHandler, 9080, codeset_version_id);
    }


}
